//
//  CompileViewController.m
//  ECO
//
//  Created by zl on 2019/9/25.
//  Copyright © 2019 谷银行. All rights reserved.
//

#import "CompileViewController.h"
#import "YYMGroup.h"
#import "CompileCell.h"// 回复语cell
#import "BjCompileCell.h"// 编辑回复语句cell
#import "ButtomBtn.h"// 底部按钮
#import "ComButtomBtn.h"// 点击编辑后的底部按钮样式
#import "AlterViewController.h"// 修改分组名称 及 添加分组
#import "ReplyuViewController.h" // 添加快捷回复语句 及 更改快捷回复语句
@interface CompileViewController ()<UITableViewDataSource, UITableViewDelegate,ButtomBtnDelegate,ComButtomBtnDelegate> {
    UIView *SlView; // 上拉菜单
    NSString *TypeCell;// 判断编辑状态
    NSString *DeletYj;// 快捷语句ID
    NSString *DeletFz;// 分组id
    BjCompileCell *BjCell;//  编辑状态中的自定义cell
    ButtomBtn *Bottom; // 点击编辑前的底部按钮样式
    ComButtomBtn *ComBtn; // 点击编辑后的底部按钮样式
}
@property(nonatomic , strong)UITableView *myTableView;
@property (nonatomic, strong) NSMutableArray      *selectArray;//记录选择的所有选项
@property (nonatomic, strong) NSMutableArray *dataArray;//数据源数组
@property (nonatomic, strong) NSArray *nameArray; // 分组数据
@property (nonatomic, strong) NSMutableArray *ListArray; // 数据源数据
@property (nonatomic, strong) NSMutableArray *ZuArray; // 数据源数据
@property (nonatomic, strong) NSMutableArray *NrArray; // 数据源数据
@end

@implementation CompileViewController
- (UITableView *)myTableView{
    if (!_myTableView) {
        _myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 150)];
        _myTableView.dataSource = self;
        _myTableView.delegate = self;
        _myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _myTableView;
}

// 取消组头悬停
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat sectionHeaderHeight = 70;
    if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
    } else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
    }
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
    [self LoadData];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"编辑";
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.myTableView];
    
    [self BottomView];
}
// 快捷语组和快捷语列表（不分页）
- (void)LoadData{
//    nameArray = [[NSArray alloc]init];
    
    NSUserDefaults *User = [NSUserDefaults standardUserDefaults];
    NSDictionary *dic = @{
                        @"kfUserId":[User objectForKey:@"kfId"],
                        @"groupType":@"1",
                        };
    
    [HttpsTool get:@"/web/find/recovery/or/group/list" params:dic success:^(id response) {
        NSLog(@"%@",response);
        SetModel *model = [SetModel yy_modelWithJSON:response];
        self.nameArray = model.data;
        for (SetData *Data in model.data) {
            [self.ListArray addObject: [Data.recoveryList yy_modelToJSONObject]];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            //绑定数据源
            [self loadDataModel];
            [self.myTableView reloadData];
        });
        
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
    }];
    
}
// 绑定数据源
- (void) loadDataModel {
    for (NSMutableArray *name in self.ListArray) {
        YYMGroup *group1 = [[YYMGroup alloc] initWithItem:name];
        [self.dataArray addObject:group1];
    }
    
}
// 底部
- (void)BottomView{
    // 底部按钮
    Bottom = [[ButtomBtn alloc]init];
    Bottom.delegate = self;
    [self.view addSubview:Bottom];
    Bottom.backgroundColor = [UIColor whiteColor];
    [Bottom mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.bottom.equalTo(self.view).offset(-5);
        make.height.equalTo(@(48));
    }];
    [Bottom.TjBtn addTarget:self action:@selector(tjBtn:) forControlEvents:UIControlEventTouchUpInside];
    SlView = [[UIView alloc]init];
    [self.view addSubview:SlView];
    // 上拉菜单
    SlView.backgroundColor = [UIColor colorWithHexString:@"#00DAAF"];
    [SlView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(Bottom.mas_top).offset(-15);
        make.right.equalTo(self.view.mas_right).offset(-15);
        make.width.equalTo(@(114));
        make.height.equalTo(@(121));
    }];
    SlView.hidden = YES;
    SlView.layer.cornerRadius = 22;
    SlView.layer.masksToBounds = YES;
    NSArray *arr = @[@"添加回复语",@"添加分组"];
    for (int i = 0; i<arr.count; i++) {
        UIButton *Btn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0+i*(121/2), 114, 121/2)];
        Btn.tag = i;
        [Btn setTitle:arr[i] forState:UIControlStateNormal];
        [Btn addTarget:self action:@selector(ButtomBtn:) forControlEvents:UIControlEventTouchUpInside];
        [SlView addSubview:Btn];
    }
    // 编辑状态中的底部按钮
    ComBtn = [[ComButtomBtn alloc]init];
    ComBtn.delegate = self;
    [self.view addSubview:ComBtn];
    [ComBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.bottom.equalTo(self.view).offset(-5);
        make.height.equalTo(@(48));
    }];
    ComBtn.hidden = YES;
    ComBtn.imgVbtn.image = [UIImage imageNamed:@"编组选中前"];
}
#pragma mark UITableViewDataSource回调方法
//这是tabview创建多少组的回调
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
    return self.nameArray.count;
    
}
//这是每个组有多少联系人的回调
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    YYMGroup *group = self.dataArray[section];
    if ([TypeCell isEqualToString:@"1"]) {
        return group.size;
    }else{
        return group.isFolded? 0: group.size;
    }
}
//将tabview的cell与数据模型绑定起来
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([TypeCell isEqualToString:@"1"]) {
        BjCell = [tableView dequeueReusableCellWithIdentifier:@"BjCell"];
        if (!BjCell) {
            BjCell = [[BjCompileCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"BjCell"];
        }
        BjCell.selectionStyle = UITableViewCellSelectionStyleNone;
        //将模型里的数据赋值给cell
        YYMGroup *group = self.dataArray[indexPath.section];
        NSArray *arr =group.items;
        NSDictionary *dic =arr[indexPath.row];
        if ([self.selectArray containsObject:dic[@"recoverContent"]]) {
            BjCell.imgV.image = [UIImage imageNamed:@"编组选中后"];
        }else {
            BjCell.imgV.image = [UIImage imageNamed:@"编组选中前"];
        }
        BjCell.name.text = dic[@"recoverContent"];
        return BjCell;
    }else{
        CompileCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CELL"];
        if (!cell) {
            cell = [[CompileCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"CELL"];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        //将模型里的数据赋值给cell
        YYMGroup *group = self.dataArray[indexPath.section];
        NSArray *arr =group.items;
        NSDictionary *dic =arr[indexPath.row];
        cell.name.text = dic[@"recoverContent"];
        
        return cell;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    YYMGroup *group = self.dataArray[indexPath.section];
    NSArray *arr=group.items;
    NSDictionary *dic =arr[indexPath.row];
    if ([TypeCell isEqualToString:@"1"]) {
//        int a = dic[@"recoveryId"];
        [self.NrArray addObject:@([dic[@"recoveryId"]integerValue])];
        if ([self.selectArray containsObject:dic[@"recoverContent"]]) {
            [self.selectArray removeObject:dic[@"recoverContent"]];
        }else {
            [self.selectArray addObject:dic[@"recoverContent"]];
        }
        
        [self.myTableView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationNone];
    }else{
        ReplyuViewController *Replyu = [ReplyuViewController new];
        Replyu.UpdataDic = dic;
        [self.navigationController pushViewController:Replyu animated:YES];
        
    }
}
#pragma mark UITableViewDelegate回调方法
//对hearderView进行编辑
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    SetData *model = self.nameArray[section];
    if ([TypeCell isEqualToString:@"1"]) {
        UIView *nameView = [[UIView alloc]init];
        UIImageView *fuhao=[[UIImageView alloc]initWithFrame:CGRectMake(15, 28, 14, 14)];
        [nameView addSubview:fuhao];
        NSArray *arr = model.recoveryList;
        NSMutableArray *array = [[NSMutableArray alloc]init];
        for (int i = 0 ; i<arr.count; i++) {
            SetDataList *list = arr[i];
            [array addObject:list.recoverContent];
        }
        NSArray *arra = array;
        //将分组的名字nameLabel添加到nameview上
        UILabel *nameLabel=[[UILabel alloc]initWithFrame:CGRectMake(35, 15, 100, 40)];
        [nameView addSubview:nameLabel];
        nameLabel.text=model.groupName;
        //添加一个button用于响应点击事件（展开还是收起）
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame=CGRectMake(0, 15, kScreenWidth, 40);
        [nameView addSubview:button];
        button.tag = section;
        BOOL selectAll = YES;
           for (id object in arra) {
               if (![self.selectArray containsObject:object]) {
                   selectAll = NO;
               }
           }
        
        if (arra.count == 0) {
            selectAll = NO;
        }
        button.selected = selectAll;
        
        if (selectAll == YES) {
            fuhao.image = [UIImage imageNamed:@"编组选中后"];
        }else{
            fuhao.image = [UIImage imageNamed:@"编组选中前"];
        }
        [button addTarget:self action:@selector(Clicked:) forControlEvents:UIControlEventTouchUpInside];
        return nameView;
    }else{
        //首先创建一个大的view，nameview
        UIView *nameView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 70)];
        //将分组的名字nameLabel添加到nameview上
        UILabel *nameLabel=[[UILabel alloc]initWithFrame:CGRectMake(15, 15, 100, 40)];
        [nameView addSubview:nameLabel];
        nameLabel.text=model.groupName;
        //将显示展开还是收起的状态通过三角符号显示出来
        UIImageView *fuhao=[[UIImageView alloc]initWithFrame:CGRectMake(120, 25, 20, 20)];
        fuhao.tag=section;
        [nameView addSubview:fuhao];
        //根据模型里面的展开还是收起变换图片
        YYMGroup *group = self.dataArray[section];
        if (group.isFolded==YES) {
            fuhao.image=[UIImage imageNamed:@"右边"];
        }else{
            fuhao.image=[UIImage imageNamed:@"下边"];
        }
        //添加一个button用于响应点击事件（展开还是收起）
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame=CGRectMake(0, 15, kScreenWidth/2, 40);
        [nameView addSubview:button];
        button.tag = 200 + section;
        [button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
        //添加一个button用于响应点击事件（修改分组名称）
        UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];
        button1.frame=CGRectMake(kScreenWidth/2, 15, kScreenWidth/2, 40);
        [nameView addSubview:button1];
        button1.tag = section;
        [button1 addTarget:self action:@selector(XgbuttonClicked:) forControlEvents:UIControlEventTouchUpInside];
        UILabel *XgLabel=[[UILabel alloc]initWithFrame:CGRectMake((kScreenWidth/2) - 40, 0, 40, 40)];
        [button1 addSubview:XgLabel];
        XgLabel.text = @"修改";
        XgLabel.font = [UIFont systemFontOfSize:12];
        XgLabel.textColor = [UIColor colorWithHexString:@"#00C9AD"];
        //返回nameView
        return nameView;
    }
}
//设置headerView高度
- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 70;
}
//设置cell的高度
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 40;
}
//button的响应点击事件(选中分组)
- (void)Clicked:(UIButton *) button {
    SetData *model = self.nameArray[button.tag];
    [self.ZuArray addObject:@(model.groupId.integerValue)];
//    DeletFz = model.groupId;
    NSArray *arr = model.recoveryList;
    NSMutableArray *array = [[NSMutableArray alloc]init];
    for (int i = 0 ; i<arr.count; i++) {
        SetDataList *list = arr[i];
        [array addObject:list.recoverContent];
    }
    
    NSArray *arra = array;
    
    if (button.selected) {
        [self.selectArray removeObjectsInArray:arra];
    }else {
        [self.selectArray addObjectsFromArray:arra];
    }

    button.selected = !button.selected;
    
    [self.myTableView reloadSections:[NSIndexSet indexSetWithIndex:button.tag] withRowAnimation:UITableViewRowAnimationNone];
}
//button的响应点击事件(打开列表 及 选中分组)
- (void) buttonClicked:(UIButton *) sender {
    //改变模型数据里面的展开收起状态
    YYMGroup *group2 = self.dataArray[sender.tag - 200];
    group2.folded = !group2.isFolded;
    [self.myTableView reloadData];
}
//button的响应点击事件
- (void) XgbuttonClicked:(UIButton *) sender {
    NSLog(@"%ld",sender.tag);
    for (int i = 0; i<self.nameArray.count; i++) {
        if (i == sender.tag) {
            SetData *model = self.nameArray[i];
            AlterViewController *alter = [[AlterViewController alloc]init];
            alter.Title = model.groupName;
            alter.GroupIdTitle = model.groupId;
            // 跳转后更改返回按钮文字
            UIBarButtonItem *returnButtonItem = [[UIBarButtonItem alloc] init];
            returnButtonItem.title = @"";
            returnButtonItem.tintColor = [UIColor blackColor];
            self.navigationItem.backBarButtonItem = returnButtonItem;
            [self.navigationController pushViewController:alter animated:YES];
        }
    }
    
}
// 添加按钮
- (void)tjBtn:(UIButton *)send{
    if (send.selected == NO) {
        send.selected = YES;
        SlView.hidden = NO;
    }else{
        SlView.hidden = YES;
        send.selected = NO;
    }
}
// 添加分组,快捷回复语 btn
- (void)ButtomBtn:(UIButton *)send{
    if (send.tag == 0) {
        if (self.nameArray.count > 0) {
            ReplyuViewController *Replyu = [ReplyuViewController new];
            Replyu.Array = self.nameArray;
            [self.navigationController pushViewController:Replyu animated:YES];
        }else{
            [BRProgressHUD showErrorWithStatus:@"请先添加快捷回复组"];
            [BRProgressHUD dismissWithDelay:1.25];
        }
        
    }else{
        AlterViewController *alter = [AlterViewController new];
        [self.navigationController pushViewController:alter animated:YES];
    }
}
// 编辑按钮代理事件
- (void)ButtomBtnClick{
    TypeCell = @"1";
    ComBtn.hidden = NO;
    Bottom.hidden = YES;
    [self.myTableView reloadData];
}
// 编辑状态中底部 全选按钮
- (void)ComButtomBtnQxClick:(UIButton *)send{
    NSMutableArray *array = [[NSMutableArray alloc]init];
    for (int i = 0; i<self.dataArray.count; i++) {
        SetData *model = self.nameArray[i];
        [self.ZuArray addObject:@(model.groupId.integerValue)];
        NSArray *arr = model.recoveryList;
        for (int i = 0 ; i<arr.count; i++) {
            SetDataList *list = arr[i];
            [array addObject:list.recoverContent];
            [self.NrArray addObject:@(list.recoveryId.integerValue)];
        }
        NSArray *arra = array;
        
        if (send.selected) {
            [self.selectArray removeObjectsInArray:arra];
            ComBtn.imgVbtn.image = [UIImage imageNamed:@"编组选中前"];
        }else {
            [self.selectArray addObjectsFromArray:arra];
            ComBtn.imgVbtn.image = [UIImage imageNamed:@"编组选中后"];
        }
    }
    
    send.selected = !send.selected;
    [self.myTableView reloadData];
}

// 编辑状态中底部 删除按钮
- (void)ComButtomBtnScClick{
    NSLog(@"++++%@",self.ZuArray);
    if (self.ZuArray.count >0 || self.NrArray.count > 0){
        NSDictionary *dic = @{
                            @"groupIds":self.ZuArray,
                            @"ids":self.NrArray
                            };
        NSLog(@"dic:%@",dic);
        
        [HttpsTool post:@"/web/del/recovery/or/group" params:dic success:^(id response) {
            NSLog(@"%@",response);
            self->DeletYj = @"";
            self->TypeCell = @"";
            self->ComBtn.hidden = YES;
            self->Bottom.hidden = NO;
            [self.myTableView reloadData];
            [self LoadData];
        } failure:^(NSError *error) {
           NSLog(@"%@",error);
        }];
    }
    else{
        TypeCell = @"";
        ComBtn.hidden = YES;
        Bottom.hidden = NO;
        [self.myTableView reloadData];
    }
    
}
- (NSMutableArray *)selectArray {
    if (!_selectArray) {
        _selectArray = [NSMutableArray arrayWithCapacity:0];
    }
    return _selectArray;
}
- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc]init];
    }
    return _dataArray;
}
- (NSArray *)nameArray{
    if (!_nameArray) {
        _nameArray = [[NSArray alloc]init];
    }
    return _nameArray;
}
-(NSMutableArray *)ListArray{
    if (!_ListArray) {
        _ListArray = [[NSMutableArray alloc]init];
    }
    return _ListArray;
}
- (NSMutableArray *)ZuArray{
    if (!_ZuArray) {
        _ZuArray = [[NSMutableArray alloc]init];
    }
    return _ZuArray;
}
- (NSMutableArray *)NrArray{
    if (!_NrArray) {
        _NrArray = [[NSMutableArray alloc]init];
    }
    return _NrArray;
}
@end

